from myelin.server.rules.Rule import Rule


class AclBaseRule(Rule):
    
    commands = {
        'remove'        : 'removeAcl',
        'remove-regex'  : 'removeAclRegex',
        'add'           : 'addAcl',
        'set'           : 'setAcl',
    }
    
    def tokenizeAclRequest(self, next):
        while next:
            p = next.find(',')
            if p == -1:             
                y = next.find(':')
                yield ( next[:y].strip(), next[y+1:],)
                break
            
            cur = next[:p]
            y = cur.find(':')
            yield ( cur[:y].strip(), cur[y+1:],)
            next = next[p+1:]
    
    def applyAcls(self, context, rule, nodeId):
        # are there any acl settings?
        # check for acls permission
        nodeAcls = context.acls.createNodeAcls(nodeId)
        if not nodeAcls.isPermittedAction('edit-acls'):
            raise "Agent does not have 'edit-acls' rights"
        
        cmds = self.commands.get
        for n in rule.rUpdate_Acls:
            for f,a in self.tokenizeAclRequest(n.rdf_value):
                if not getattr(nodeAcls,cmds(f))(a):
                    raise "Got an error while trying to updating acls: %s, %s" % (f,a)